#include"Sort.h"
void SortPrint(int* a,int n)
{
	for (int i = 0; i < n; i++)
	{
		printf("%d ", a[i]);
	}
	printf("\n");
}
void Swap(int* p1, int* p2)
{
	int tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}
//冒泡排序
void BubbleSort1(int* a, int n)
{
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n -1- i; j++)
		{
			if (a[j] > a[j + 1])
			{
				Swap(&a[j], &a[j + 1]);
			}
		}
	}
}
//冒泡排序优化版1
void BubbleSort2(int* a, int n)
{
	for (int j = 0; j < n; j++)
	{
		int flag = 0;
		for (int i = 1; i < n - j; i++)
		{
			if (a[i - 1] > a[i])
			{
				Swap(&a[i - 1], &a[i]);
				flag = 1;
			}
		}
		if (flag == 0)
		{
			break;
		}
	}
}
//冒泡排序优化版2
void BubbleSort3(int* a, int n)
{
	int end = n;
	while (end > 0)
	{
		int lastSwap = 0;
		for (int i = 1; i < end; i++)
		{
			if (a[i - 1] > a[i])
			{
				Swap(&a[i - 1], &a[i]);
				lastSwap = i;
			}
		}
		end = lastSwap;
	}
}
//插入排序
void InsertSort(int* a, int n)
{
	for (int i = 0; i < n - 1; i++)
	{
		int end = i;
		int tmp = a[end + 1];
		while (end >= 0)
		{
			if (tmp < a[end])
			{
				a[end + 1] = a[end];
				--end;
			}
			else
			{
				break;
			}
		}
		a[end + 1] = tmp;
	}
}
//希尔排序
void ShellSort(int* a, int n)
{
	int gap = n;
	while (gap > 1)
	{
		gap = gap / 3 + 1;
		for (int i = 0; i < n - gap; ++i)
		{
			int end = i;
			int tmp = a[end + gap];
			while (end >= 0)
			{
				if (tmp < a[end])
				{
					a[end + gap] = a[end];
					end -= gap;
				}
				else
				{
					break;
				}
			}
			a[end + gap] = tmp;
		}
	}
}
int main()
{
	srand((unsigned int)time(0));
	const int N = 10;
	int* a1 = (int*)malloc(sizeof(int) * N);
	int* a2 = (int*)malloc(sizeof(int) * N);
	int* a3 = (int*)malloc(sizeof(int) * N);
	int* a4 = (int*)malloc(sizeof(int) * N);
	int* a5 = (int*)malloc(sizeof(int) * N);
	for (int i = 0; i < N; i++)
	{
		a1[i] = rand() + i;
		//a2[i] = a1[i];
		a3[i] = a1[i];
		a4[i] = a1[i];
		a5[i] = a1[i];
	}
	//int begin1 = clock();
	//BubbleSort1(a1, N);
	//int end1 = clock();

	//int begin2 = clock();
	//BubbleSort2(a2, N);
	//int end2 = clock();

	int begin3 = clock();
	BubbleSort3(a3, N);
	int end3 = clock();

	int begin4 = clock();
	InsertSort(a4, N);
	int end4 = clock();

	int begin5 = clock();
	ShellSort(a5, N);
	int end5 = clock();

	//printf("BubbleSort1:%d \n", end1 - begin1);
	//printf("BubbleSort2:%d \n", end2 - begin2);
	printf("BubbleSort3:%d \n", end3 - begin3);
	printf("InsertSort:%d \n", end4 - begin4);
	printf("ShellSort:%d \n", end5 - begin5);

	SortPrint(a3, N);
	SortPrint(a4, N);
	SortPrint(a5, N);
	
	free(a1);
	free(a3);
	free(a4);
	free(a5);
	return 0;
}